import java.util.IdentityHashMap;

public class Variable extends Term {
    String name; boolean bound; Term value;
    public Variable(String name) {
        this.name = name;
        this.kind = Kind.VARIABLE;
        unbind();
    }
    
    public Term dereference() {
        if(bound) return value.dereference();
        return this;
    }
    
    public void bindTo(Term t) {
        bound = true;
        value = t;
        
        //System.out.println(" % " + name + " := " + t);
    }
    
    public void unbind() {
        bound = false;
        value = null;
        
        //System.out.println(" % !" + name);
    }
    
    public String toString() {
        if(!bound) return name;
        return dereference().toString();
    }
    
    public Stack<Term> fromPrologList() {
        Term t = dereference();
        if(t.kind == Kind.VARIABLE) {
            return null;
        }
        else {
            return t.fromPrologList();
        }
    }
    
    public Term copy_term(IdentityHashMap<Term,Term> map) {
        if(bound) {
            return value.copy_term(map);
        }
        else {
            Term result = map.get(this);
            if(result == null) {
                result = new Variable(name);
                map.put(this,result);
                return result;
            }
            else {
                return result;
            }
        }
    }
}
